package menu;

import javax.microedition.lcdui.*;
import java.util.*;

/**
 * Cascading Menu design pattern.
 * MenuElement can be a menu container as well as a menu item.
 *
 * @author Ben Hui
 */

public class MenuElement implements CommandListener
{
  public Vector children = new Vector(); // menu item in this menu container
  Hashtable menuMap = new Hashtable(); // menu item to next screen mapping

  public String text; // menu label or title

  /**
   * Constructor.
   * For menu container, parameters s is the title of the menu.
   * For menu item, s is the label of the item
   * @param s title or label of menu
   */
  public MenuElement( String s )
  {
    text = s;
  }

  /**
   * For menu container, add a menu item, and link this item to another container when user
   * select it.
   * @param child a menu item
   * @param next_container the next menu to show when this item is selected
   */
  public void addChild( MenuElement child, MenuElement next_container )
  {
    children.addElement( child );
    menuMap.put( child, next_container );
  }

  /**
   * For menu container, add a menu item, and link this item to another Displayable object when user
   * select it.
   * @param child a menu item
   * @param display the next screen show when this item is selected
   */
  public void addChild( MenuElement child, Displayable display )
  {
    children.addElement( child );
    menuMap.put( child, display );

  }

  public void commandAction(Command command, Displayable displayable)
  {
    if ( command.equals( List.SELECT_COMMAND ) && displayable instanceof MenuList )
    {
      MenuList list = (MenuList) displayable;
      int i = list.getSelectedIndex();
      MenuElement item = (MenuElement) children.elementAt( i );
      Object next = menuMap.get( item );

      if ( next instanceof MenuElement )
      {
        list.showMenu( (MenuElement) next );

      } else if ( next instanceof MDisplayable && next instanceof Displayable )
      {
        ((MDisplayable)next).onDisplay( item );
        list.getDisplay().setCurrent( (Displayable) next );

      } else if ( next instanceof Displayable )
      {
        list.getDisplay().setCurrent( (Displayable) next );
      }
    }
  }
}
